<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>学海教育 - 教师工作台</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }

    :root {
      --primary: #4a6bff;
      --secondary: #6c757d;
      --success: #28a745;
      --warning: #ffc107;
      --danger: #dc3545;
      --light: #f8f9fa;
      --dark: #343a40;
      --border-radius: 8px;
      --box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      --transition: all 0.3s ease;
    }

    body {
      background-color: #f5f7fb;
      color: #333;
      line-height: 1.6;
    }

    .container {
      display: flex;
      min-height: 100vh;
    }

    /* 侧边栏样式 */
    .sidebar {
      width: 250px;
      background: linear-gradient(to bottom, #4a6bff, #3a5bd9);
      color: white;
      padding: 20px 0;
      box-shadow: var(--box-shadow);
      z-index: 100;
    }

    .logo {
      display: flex;
      align-items: center;
      padding: 0 20px 20px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      margin-bottom: 20px;
    }

    .logo i {
      font-size: 28px;
      margin-right: 10px;
    }

    .logo h1 {
      font-size: 20px;
    }

    .user-info {
      padding: 0 20px 20px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      margin-bottom: 20px;
    }

    .user-avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background-color: rgba(255, 255, 255, 0.2);
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-weight: bold;
      margin-right: 10px;
    }
    
    .logout-btn {
      background: rgba(220, 53, 69, 0.8);
      color: white;
      border: none;
      padding: 8px 12px;
      border-radius: var(--border-radius);
      cursor: pointer;
      font-size: 14px;
      transition: var(--transition);
      display: flex;
      align-items: center;
      justify-content: center;
      margin-left: auto;
    }
    
    .logout-btn:hover {
      background: rgba(220, 53, 69, 1);
      transform: translateY(-1px);
    }

    .nav-links {
      list-style: none;
    }

    .nav-links li {
      padding: 12px 20px;
      margin: 5px 0;
      cursor: pointer;
      transition: var(--transition);
      display: flex;
      align-items: center;
    }

    .nav-links li.active {
      background-color: rgba(255, 255, 255, 0.15);
      border-left: 4px solid white;
    }

    .nav-links li:hover {
      background-color: rgba(255, 255, 255, 0.1);
    }

    .nav-links i {
      margin-right: 12px;
      font-size: 18px;
    }

    /* 主内容区样式 */
    .main-content {
      flex: 1;
      padding: 20px;
      overflow-y: auto;
    }

    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30px;
      padding-bottom: 15px;
      border-bottom: 1px solid #eaeaea;
    }

    .header h2 {
      color: var(--dark);
    }

    .action-buttons {
      display: flex;
      gap: 10px;
    }

    /* 内容卡片样式 */
    .content-section {
      display: none;
    }

    .content-section.active {
      display: block;
      animation: fadeIn 0.5s ease;
    }

    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(10px); }
      to { opacity: 1; transform: translateY(0); }
    }

    .section-title {
      font-size: 24px;
      margin-bottom: 20px;
      color: var(--dark);
      display: flex;
      align-items: center;
    }

    .section-title i {
      margin-right: 10px;
      color: var(--primary);
    }

    .card-container {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 20px;
    }

    .card {
      background-color: white;
      border-radius: var(--border-radius);
      box-shadow: var(--box-shadow);
      overflow: hidden;
      transition: var(--transition);
    }

    .card:hover {
      transform: translateY(-5px);
      box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
    }

    .card-header {
      padding: 15px;
      background-color: var(--primary);
      color: white;
    }

    .card-body {
      padding: 15px;
    }

    .card-footer {
      padding: 15px;
      border-top: 1px solid #eaeaea;
      display: flex;
      justify-content: space-between;
    }

    .btn {
      padding: 8px 16px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-weight: 500;
      transition: var(--transition);
    }

    .btn-primary {
      background-color: var(--primary);
      color: white;
    }

    .btn-primary:hover {
      background-color: #3a5bd9;
    }

    .btn-success {
      background-color: var(--success);
      color: white;
    }

    .btn-success:hover {
      background-color: #218838;
    }

    .btn-warning {
      background-color: var(--warning);
      color: var(--dark);
    }

    .btn-warning:hover {
      background-color: #e0a800;
    }

    .btn-outline {
      background-color: transparent;
      border: 1px solid var(--primary);
      color: var(--primary);
    }

    .btn-outline:hover {
      background-color: var(--primary);
      color: white;
    }

    .stats {
      display: flex;
      gap: 15px;
      margin-top: 10px;
    }

    .stat-item {
      display: flex;
      align-items: center;
      font-size: 14px;
    }

    .stat-item i {
      margin-right: 5px;
      color: var(--primary);
    }

    /* 表单样式 */
    .form-container {
      background-color: white;
      border-radius: var(--border-radius);
      box-shadow: var(--box-shadow);
      padding: 25px;
      max-width: 600px;
    }

    .form-group {
      margin-bottom: 20px;
    }

    .form-group label {
      display: block;
      margin-bottom: 8px;
      font-weight: 500;
      color: var(--dark);
    }

    .form-control {
      width: 100%;
      padding: 10px 12px;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 15px;
      transition: var(--transition);
    }

    .form-control:focus {
      border-color: var(--primary);
      outline: none;
    }

    textarea.form-control {
      min-height: 120px;
      resize: vertical;
    }

    /* 课程详情页面 */
    .course-detail-header {
      background-color: white;
      border-radius: var(--border-radius);
      box-shadow: var(--box-shadow);
      padding: 20px;
      margin-bottom: 20px;
    }

    .course-tabs {
      display: flex;
      border-bottom: 1px solid #eaeaea;
      margin-bottom: 20px;
    }

    .course-tab {
      padding: 12px 20px;
      cursor: pointer;
      font-weight: 500;
      color: var(--secondary);
      transition: var(--transition);
      border-bottom: 2px solid transparent;
    }

    .course-tab.active {
      color: var(--primary);
      border-bottom-color: var(--primary);
    }

    .tab-content {
      display: none;
    }

    .tab-content.active {
      display: block;
    }

    .chapter-list {
      list-style: none;
    }

    .chapter-item {
      padding: 20px;
      border: 1px solid #eaeaea;
      border-radius: var(--border-radius);
      margin-bottom: 15px;
      background-color: white;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    }

    .chapter-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
    }

    .chapter-info {
      display: flex;
      align-items: center;
    }

    .chapter-number {
      width: 30px;
      height: 30px;
      border-radius: 50%;
      background-color: var(--primary);
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;
      font-weight: 500;
    }

    .chapter-actions {
      display: flex;
      gap: 8px;
    }

    .materials-section {
      margin-top: 15px;
      padding-top: 15px;
      border-top: 1px solid #f0f0f0;
    }

    .materials-title {
      font-weight: 500;
      color: var(--dark);
      margin-bottom: 10px;
      font-size: 14px;
    }

    .materials-list {
      list-style: none;
      margin: 0;
      padding: 0;
    }

    .material-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 12px;
      background-color: #f8f9fa;
      border-radius: 6px;
      margin-bottom: 8px;
      border: 1px solid #e9ecef;
    }

    .material-info {
      display: flex;
      align-items: center;
      flex: 1;
    }

    .material-icon {
      margin-right: 10px;
      color: var(--primary);
      font-size: 16px;
    }

    .upload-material {
      background-color: var(--success);
      color: white;
      border: none;
    }

    .upload-material:hover {
      background-color: #218838;
    }

    .student-list {
      list-style: none;
    }

    .student-item {
      padding: 12px 15px;
      border: 1px solid #eaeaea;
      border-radius: var(--border-radius);
      margin-bottom: 10px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .student-item.pending {
      border-left: 4px solid var(--warning);
      background-color: #fff8e1;
    }
    
    .student-item.approved {
      border-left: 4px solid var(--success);
      background-color: #e8f5e9;
    }
    
    .student-item.rejected {
      border-left: 4px solid var(--danger);
      background-color: #ffebee;
    }

    .student-info {
      display: flex;
      align-items: center;
    }

    .student-avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background-color: var(--primary);
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;
      font-weight: 500;
    }

    .progress-bar {
      height: 6px;
      background-color: #e9ecef;
      border-radius: 3px;
      margin: 10px 0;
      overflow: hidden;
    }

    .progress {
      height: 100%;
      background-color: var(--success);
      border-radius: 3px;
    }
    
    .status-badge {
      padding: 4px 8px;
      border-radius: 20px;
      font-size: 12px;
      font-weight: 500;
      margin-right: 10px;
    }
    
    .status-pending {
      background-color: #fff3e0;
      color: #ff9800;
    }
    
    .status-approved {
      background-color: #e8f5e9;
      color: var(--success);
    }
    
    .status-rejected {
      background-color: #ffebee;
      color: var(--danger);
    }
    
    .approval-buttons {
      display: flex;
      gap: 5px;
    }
    
    .btn-sm {
      padding: 4px 8px;
      font-size: 12px;
    }

    /* 模态框样式 */
    .modal {
      display: none;
      position: fixed;
      z-index: 1000;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.5);
    }

    .modal-content {
      background-color: white;
      margin: 15% auto;
      padding: 20px;
      border-radius: var(--border-radius);
      width: 400px;
      max-width: 90%;
      box-shadow: var(--box-shadow);
    }

    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 1px solid #eaeaea;
    }

    .modal-header h3 {
      margin: 0;
      color: var(--dark);
    }

    .close {
      color: #aaa;
      font-size: 28px;
      font-weight: bold;
      cursor: pointer;
    }

    .close:hover {
      color: var(--dark);
    }

    .modal-footer {
      display: flex;
      gap: 10px;
      justify-content: flex-end;
      margin-top: 20px;
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
      .container {
        flex-direction: column;
      }

      .sidebar {
        width: 100%;
        padding: 10px 0;
      }

      .nav-links {
        display: flex;
        justify-content: space-around;
      }

      .nav-links li {
        flex-direction: column;
        text-align: center;
        padding: 10px;
        font-size: 14px;
      }

      .nav-links li.active {
        border-left: none;
        border-bottom: 3px solid white;
      }

      .nav-links i {
        margin-right: 0;
        margin-bottom: 5px;
      }

      .card-container {
        grid-template-columns: 1fr;
      }

      .header {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
      }

      .action-buttons {
        width: 100%;
        justify-content: space-between;
      }
    }

    /* 作业列表样式 */
    .homework-list {
      list-style: none;
      padding: 0;
      margin: 0;
    }

    .homework-item {
      background: white;
      border: 1px solid #e0e0e0;
      border-radius: 8px;
      padding: 20px;
      margin-bottom: 16px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.05);
      transition: var(--transition);
    }

    .homework-item:hover {
      box-shadow: 0 4px 12px rgba(0,0,0,0.1);
      transform: translateY(-2px);
    }

    .homework-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 12px;
    }

    .homework-info h5 {
      margin: 0 0 8px 0;
      color: var(--dark);
      font-size: 18px;
    }

    .homework-meta {
      display: flex;
      gap: 16px;
      font-size: 14px;
      color: var(--secondary);
    }

    .homework-meta span {
      display: flex;
      align-items: center;
      gap: 4px;
    }

    .homework-actions {
      display: flex;
      gap: 8px;
    }

    .homework-content {
      margin-bottom: 16px;
      line-height: 1.6;
      color: #555;
    }

    .homework-status {
      display: inline-block;
      padding: 4px 12px;
      border-radius: 20px;
      font-size: 12px;
      font-weight: 500;
    }

    .homework-status.active {
      background: #e8f5e8;
      color: #2d5a2d;
    }

    .homework-status.expired {
      background: #ffeaea;
      color: #d32f2f;
    }

    .homework-status.upcoming {
      background: #fff3e0;
      color: #f57c00;
    }
  </style>
</head>
<body>
<div class="container">
  <!-- 侧边导航栏 -->
  <div class="sidebar">
    <div class="logo">
      <i class="fas fa-graduation-cap"></i>
      <h1>学海教育</h1>
    </div>

    <div class="user-info">
      <div class="user-avatar" th:text="${#strings.substring(user.username, 0, 1)}">王</div>
      <div>
        <div th:text="${user.username}">王教授</div>
        <div style="font-size: 12px; opacity: 0.8;">教师</div>
      </div>
      <button class="logout-btn" onclick="logout()">
        <i class="fas fa-sign-out-alt"></i>
      </button>
    </div>

    <ul class="nav-links">
      <li class="active" data-target="my-courses">
        <i class="fas fa-book-open"></i>
        <span>我的课程</span>
      </li>
      <li data-target="create-course">
        <i class="fas fa-plus-circle"></i>
        <span>创建课程</span>
      </li>
    </ul>
  </div>

  <!-- 主内容区 -->
  <div class="main-content">
    <div class="header">
      <h2>教师工作台</h2>
    </div>

    <!-- 我的课程 -->
    <div class="content-section active" id="my-courses">
      <h3 class="section-title">
        <i class="fas fa-book-open"></i>
        我的课程
      </h3>

      <div class="card-container" id="my-course-list"></div>
    </div>

    <!-- 创建课程 -->
    <div class="content-section" id="create-course">
      <h3 class="section-title">
        <i class="fas fa-plus-circle"></i>
        创建新课程
      </h3>

      <div class="form-container">
        <form id="course-form">
          <div class="form-group">
            <label for="course-name">课程名称</label>
            <input type="text" id="course-name"  class="form-control" placeholder="请输入课程名称" required>
          </div>

          <!--
          <div class="form-group">
            <label for="course-category">课程分类</label>
            <select id="course-category" class="form-control" required>
              <option value="">请选择课程分类</option>
              <option value="math">数学</option>
              <option value="programming">编程</option>
              <option value="language">语言</option>
              <option value="science">科学</option>
              <option value="arts">艺术</option>
            </select>
          </div>
          -->

          <div class="form-group">
            <label for="course-description">课程描述</label>
            <textarea id="course-description" class="form-control" placeholder="请简要描述课程内容" required></textarea>
          </div>

<!--          <div class="form-group">-->
<!--            <label for="course-duration">课程时长（周）</label>-->
<!--            <input type="number" id="course-duration" class="form-control" min="1" max="52" value="12" required>-->
<!--          </div>-->

          <!--
          <div class="form-group">
            <label for="course-level">难度级别</label>
            <select id="course-level" class="form-control" required>
              <option value="beginner">初级</option>
              <option value="intermediate" selected>中级</option>
              <option value="advanced">高级</option>
            </select>
          </div>
          -->

          <!--
          <div class="form-group">
            <label for="course-image">课程封面</label>
            <input type="file" id="course-image" class="form-control">
          </div>
          -->

          <div style="display: flex; gap: 10px; margin-top: 25px;">
            <button type="button" class="btn btn-outline" style="flex: 1;">取消</button>
            <button type="submit" class="btn btn-primary" style="flex: 1;">创建课程</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 课程详情 -->
    <div class="content-section" id="course-detail">
      <div class="course-detail-header">
        <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 15px;">
          <div>
            <h3 id="detail-course-name">高等数学</h3>
            <p id="detail-course-info">已开课 · 128名学生 · 12章节</p>
          </div>
          <button class="btn btn-outline" id="back-to-courses">
            <i class="fas fa-arrow-left"></i> 返回课程列表
          </button>
        </div>

        <div class="course-tabs">
          <div class="course-tab active" data-tab="chapters">章节管理</div>
          <div class="course-tab" data-tab="students">学生列表</div>
          <div class="course-tab" data-tab="assignments">作业管理</div>
          <div class="course-tab" data-tab="analytics">课程数据</div>
        </div>
      </div>

      <!-- 章节管理 -->
      <div class="tab-content active" id="chapters-tab">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
          <h4>课程章节</h4>
            <button class="btn btn-success" id="add-chapter-btn">
              <i class="fas fa-plus"></i> 添加章节
           </button>
        </div>
        
        <ul class="chapter-list" id="chapter-list-container">
          <!-- 章节列表将通过JavaScript动态加载 -->
        </ul>
      </div>

      <!-- 学生列表 -->
      <div class="tab-content" id="students-tab">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
          <h4>选课学生</h4>
          <div>
            <button class="btn btn-outline" id="refresh-students">
              <i class="fas fa-sync-alt"></i> 刷新
            </button>
            <button class="btn btn-outline">
              <i class="fas fa-download"></i> 导出名单
            </button>
          </div>
        </div>

        <div id="students-loading" style="text-align: center; padding: 20px; display: none;">
          <i class="fas fa-spinner fa-spin"></i> 加载中...
        </div>

        <ul class="student-list" id="student-list-container">
          <!-- 学生列表将通过JavaScript动态加载 -->
        </ul>
        
        <div id="no-students" style="text-align: center; padding: 40px; color: #666; display: none;">
          <i class="fas fa-users" style="font-size: 48px; margin-bottom: 20px; opacity: 0.3;"></i>
          <h3>暂无学生选课</h3>
          <p>当前课程还没有学生申请选课</p>
        </div>
      </div>

      <!-- 作业管理 -->
      <div class="tab-content" id="assignments-tab">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
          <h4>作业管理</h4>
          <button class="btn btn-success" id="create-homework-btn">
            <i class="fas fa-plus"></i> 布置作业
          </button>
        </div>

        <!-- 作业列表 -->
        <div id="homework-list-container">
          <div id="homework-loading" style="text-align: center; padding: 20px; display: none;">
            <i class="fas fa-spinner fa-spin"></i> 加载中...
          </div>
          <div id="no-homework" style="text-align: center; padding: 40px; color: #666; display: none;">
            <i class="fas fa-clipboard-list" style="font-size: 48px; margin-bottom: 16px; color: #ddd;"></i>
            <h3>暂无作业</h3>
            <p>还没有布置任何作业，点击"布置作业"开始创建</p>
          </div>
          <ul id="homework-list" class="homework-list">
            <!-- 作业列表将通过JavaScript动态加载 -->
          </ul>
        </div>
      </div>

      <!-- 课程数据 -->
      <div class="tab-content" id="analytics-tab">
        <h4>课程数据统计</h4>
        <p>数据分析功能正在开发中...</p>
      </div>
    </div>
  </div>

  <!-- 添加章节模态框 -->
  <div id="addChapterModal" class="modal">
    <div class="modal-content">
      <div class="modal-header">
        <h3>添加章节</h3>
        <span class="close">&times;</span>
      </div>
      <form id="addChapterForm">
        <div class="form-group">
          <label for="chapterTitle">章节名称</label>
          <input type="text" id="chapterTitle" class="form-control" placeholder="请输入章节名称" required>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline" id="cancelChapter">取消</button>
          <button type="submit" class="btn btn-primary">添加章节</button>
        </div>
      </form>
    </div>
  </div>

  <!-- 课件上传模态框 -->
  <div id="uploadMaterialModal" class="modal">
    <div class="modal-content">
      <div class="modal-header">
        <h3>上传课件</h3>
        <span class="close" id="closeUploadModal">&times;</span>
      </div>
      <form id="uploadMaterialForm" enctype="multipart/form-data">
        <div class="form-group">
          <label for="materialFile">选择文件</label>
          <input type="file" id="materialFile" class="form-control" accept=".pdf,.doc,.docx,.ppt,.pptx,.txt" required>
          <small style="color: var(--secondary); font-size: 12px;">支持格式：PDF, DOC, DOCX, PPT, PPTX, TXT</small>
        </div>
        <div class="form-group">
          <label for="materialName">文件名称</label>
          <input type="text" id="materialName" class="form-control" placeholder="请输入文件名称" required>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline" id="cancelUpload">取消</button>
          <button type="submit" class="btn btn-primary">上传课件</button>
        </div>
      </form>
    </div>
  </div>

  <!-- 删除确认模态框 -->
  <div id="deleteConfirmModal" class="modal">
    <div class="modal-content" style="max-width: 400px;">
      <div class="modal-header">
        <h3>确认删除</h3>
        <span class="close" id="closeDeleteModal">&times;</span>
      </div>
      <div class="modal-body">
        <p id="deleteMessage">确定要删除这个项目吗？</p>
        <p style="color: var(--danger); font-size: 14px; margin-top: 10px;">
          <i class="fas fa-exclamation-triangle"></i> 此操作不可撤销！
        </p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline" id="cancelDelete">取消</button>
        <button type="button" class="btn btn-danger" id="confirmDelete">确认删除</button>
      </div>
    </div>
  </div>

  <!-- 布置作业模态框 -->
  <div id="homeworkModal" class="modal">
    <div class="modal-content" style="max-width: 600px;">
      <div class="modal-header">
        <h3>布置作业</h3>
        <span class="close" id="closeHomeworkModal">&times;</span>
      </div>
      <form id="homeworkForm">
        <div class="modal-body">
          <div class="form-group">
            <label for="homeworkTitle">作业标题</label>
            <input type="text" id="homeworkTitle" class="form-control" placeholder="请输入作业标题" required>
          </div>
          <div class="form-group">
            <label for="homeworkContent">作业内容</label>
            <textarea id="homeworkContent" class="form-control" rows="6" placeholder="请详细描述作业要求和内容" required></textarea>
          </div>
          <div class="form-group">
            <label for="homeworkDdlTime">截止时间</label>
            <input type="datetime-local" id="homeworkDdlTime" class="form-control" required>
          </div>
          <div class="form-group">
            <label for="homeworkTotalScore">总分</label>
            <input type="number" id="homeworkTotalScore" class="form-control" value="100" min="1" max="1000" step="0.1" required>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline" id="cancelHomework">取消</button>
          <button type="submit" class="btn btn-primary">布置作业</button>
        </div>
      </form>
    </div>
  </div>

  <!-- 编辑作业模态框 -->
  <div id="editHomeworkModal" class="modal">
    <div class="modal-content" style="max-width: 600px;">
      <div class="modal-header">
        <h3>编辑作业</h3>
        <span class="close" id="closeEditHomeworkModal">&times;</span>
      </div>
      <form id="editHomeworkForm">
        <input type="hidden" id="editHomeworkId">
        <div class="modal-body">
          <div class="form-group">
            <label for="editHomeworkTitle">作业标题</label>
            <input type="text" id="editHomeworkTitle" class="form-control" placeholder="请输入作业标题" required>
          </div>
          <div class="form-group">
            <label for="editHomeworkContent">作业内容</label>
            <textarea id="editHomeworkContent" class="form-control" rows="6" placeholder="请详细描述作业要求和内容" required></textarea>
          </div>
          <div class="form-group">
            <label for="editHomeworkDdlTime">截止时间</label>
            <input type="datetime-local" id="editHomeworkDdlTime" class="form-control" required>
          </div>
          <div class="form-group">
            <label for="editHomeworkTotalScore">总分</label>
            <input type="number" id="editHomeworkTotalScore" class="form-control" value="100" min="1" max="1000" step="0.1" required>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline" id="cancelEditHomework">取消</button>
          <button type="submit" class="btn btn-primary">保存修改</button>
        </div>
      </form>
    </div>
  </div>

  <!-- 查看作业提交模态框 -->
  <div id="submissionsModal" class="modal">
    <div class="modal-content" style="max-width: 800px;">
      <div class="modal-header">
        <h3>作业提交情况</h3>
        <span class="close" id="closeSubmissionsModal">&times;</span>
      </div>
      <div class="modal-body">
        <div id="submissions-loading" style="text-align: center; padding: 20px; display: none;">
          <i class="fas fa-spinner fa-spin"></i> 加载中...
        </div>
        <div id="no-submissions" style="text-align: center; padding: 40px; color: #666; display: none;">
          <i class="fas fa-users" style="font-size: 48px; margin-bottom: 16px; color: #ddd;"></i>
          <h3>暂无提交</h3>
          <p>还没有学生提交这个作业</p>
        </div>
        <div id="submissions-list">
          <!-- 提交列表将通过JavaScript动态加载 -->
        </div>
      </div>
    </div>
  </div>
</div>

<script>
  // 全局变量
  let currentCourseId = null;
  let deleteType = null; // 'chapter' 或 'material'
  let deleteId = null;
  let deleteChapterId = null; // 用于课件删除时记录章节ID

  // 章节删除功能
  function deleteChapter(chapterId, chapterName) {
    deleteType = 'chapter';
    deleteId = chapterId;
    const deleteMessage = document.getElementById('deleteMessage');
    const deleteModal = document.getElementById('deleteConfirmModal');
    deleteMessage.textContent = `确定要删除章节"${chapterName}"吗？删除后该章节下的所有课件也将被删除。`;
    deleteModal.style.display = 'block';
  }

  // 课件删除功能
  function deleteMaterial(materialId, chapterId) {
    deleteType = 'material';
    deleteId = materialId;
    deleteChapterId = chapterId;
    const deleteMessage = document.getElementById('deleteMessage');
    const deleteModal = document.getElementById('deleteConfirmModal');
    deleteMessage.textContent = '确定要删除这个课件吗？';
    deleteModal.style.display = 'block';
  }

  // 确认删除
  function confirmDelete() {
    if (deleteType === 'chapter') {
      deleteChapterConfirm();
    } else if (deleteType === 'material') {
      deleteMaterialConfirm();
    }
  }

  // 执行章节删除
  function deleteChapterConfirm() {
    const deleteModal = document.getElementById('deleteConfirmModal');
    const confirmBtn = document.getElementById('confirmDelete');
    
    // 防止重复点击
    if (confirmBtn.disabled) {
      return;
    }
    
    // 禁用确认按钮
    confirmBtn.disabled = true;
    confirmBtn.textContent = '删除中...';
    
    fetch(`/teacher/course/chapter/delete`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: `chapterId=${deleteId}`
    })
    .then(response => {
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }
      return response.text();
    })
    .then(result => {
      if (result === 'ok') {
        alert('章节删除成功！');
        // 重新加载章节列表
        if (currentCourseId) {
          loadCourseChapters(currentCourseId);
        }
      } else {
        alert('删除失败：' + result);
      }
    })
    .catch(err => {
      console.error('删除章节失败:', err);
      alert('删除失败：' + err.message);
    })
    .finally(() => {
      // 恢复按钮状态
      confirmBtn.disabled = false;
      confirmBtn.textContent = '确认删除';
      deleteModal.style.display = 'none';
    });
  }

  // 加载课程章节列表
  function loadCourseChapters(courseId) {
    fetch(`/teacher/course/chapters?courseId=${courseId}`)
      .then(r => r.json())
      .then(chapters => {
        const chapterList = document.getElementById('chapter-list-container');
        if (!chapterList) return;
        
        chapterList.innerHTML = '';
        
        if (!Array.isArray(chapters) || chapters.length === 0) {
          chapterList.innerHTML = '<li style="text-align:center;color:#666;padding:20px;">当前暂无章节</li>';
          return;
        }
        
        chapters.forEach((chapter, index) => {
          const chapterItem = document.createElement('li');
          chapterItem.className = 'chapter-item';
          chapterItem.innerHTML = `
            <div class="chapter-header">
              <div class="chapter-info">
                <div class="chapter-number">${index + 1}</div>
                <div>
                  <div style="font-weight: 500;">${chapter.title || ''}</div>
                  <div style="font-size: 14px; color: var(--secondary);">3课时 · 45分钟</div>
                </div>
              </div>
              <div class="chapter-actions">
                <button class="btn btn-outline btn-sm upload-material" data-chapter="${chapter.id}">
                  <i class="fas fa-upload"></i> 上传课件
                </button>
                <button class="btn btn-outline btn-sm edit-chapter" data-chapter="${chapter.id}">
                  <i class="fas fa-edit"></i> 编辑
                </button>
                <button class="btn btn-outline btn-sm delete-chapter" data-chapter="${chapter.id}" data-chapter-name="${chapter.title}">
                  <i class="fas fa-trash"></i> 删除
                </button>
              </div>
            </div>
            <div class="materials-section">
              <div class="materials-title">
                <span>课件列表</span>
              </div>
              <ul class="materials-list" id="materials-${chapter.id}">
                <!-- 课件列表将通过JavaScript动态加载 -->
              </ul>
            </div>`;
          chapterList.appendChild(chapterItem);
          
          // 加载该章节的课件列表
          loadChapterMaterials(courseId, chapter.id);
        });
      })
      .catch(err => {
        console.error(err);
        const chapterList = document.getElementById('chapter-list-container');
        if (chapterList) {
          chapterList.innerHTML = '<li style="text-align:center;color:#c62828;padding:20px;">加载章节失败</li>';
        }
      });
  }

  // 根据文件类型获取图标
  function getFileIcon(contentType) {
    if (!contentType) return 'fa-file';
    
    if (contentType.includes('pdf')) return 'fa-file-pdf';
    if (contentType.includes('word') || contentType.includes('document')) return 'fa-file-word';
    if (contentType.includes('powerpoint') || contentType.includes('presentation')) return 'fa-file-powerpoint';
    if (contentType.includes('text')) return 'fa-file-alt';
    if (contentType.includes('image')) return 'fa-file-image';
    if (contentType.includes('video')) return 'fa-file-video';
    if (contentType.includes('audio')) return 'fa-file-audio';
    
    return 'fa-file';
  }

  // 下载课件
  function downloadMaterial(materialId) {
    window.open(`/teacher/course/material/${materialId}/download`, '_blank');
  }

  // 加载章节课件列表
  function loadChapterMaterials(courseId, chapterId) {
    fetch(`/teacher/course/${courseId}/chapter/${chapterId}/materials`)
      .then(r => r.json())
      .then(materials => {
        const materialsList = document.getElementById(`materials-${chapterId}`);
        if (!materialsList) return;
        
        materialsList.innerHTML = '';
        
        if (!Array.isArray(materials) || materials.length === 0) {
          materialsList.innerHTML = '<li style="text-align:center;color:#999;padding:10px;font-size:12px;">暂无课件</li>';
          return;
        }
        
        materials.forEach(material => {
          const materialItem = document.createElement('li');
          materialItem.className = 'material-item';
          
          // 根据文件类型选择图标
          const fileIcon = getFileIcon(material.content_type || material.name);
          
          materialItem.innerHTML = `
            <div class="material-info">
              <i class="fas ${fileIcon} material-icon"></i>
              <div>
                <div>${material.name || ''}</div>
                <div style="font-size: 12px; color: var(--secondary);">上传于 ${material.created_at || ''}</div>
              </div>
            </div>
            <div>
              <button class="btn btn-outline btn-sm" onclick="downloadMaterial(${material.id})">
                <i class="fas fa-download"></i> 下载
              </button>
              <button class="btn btn-outline btn-sm" onclick="deleteMaterial(${material.id}, ${chapterId})">
                <i class="fas fa-trash"></i> 删除
              </button>
            </div>`;
          materialsList.appendChild(materialItem);
        });
      })
      .catch(err => {
        console.error(err);
        const materialsList = document.getElementById(`materials-${chapterId}`);
        if (materialsList) {
          materialsList.innerHTML = '<li style="text-align:center;color:#c62828;padding:10px;font-size:12px;">加载失败</li>';
        }
      });
  }

  // 执行课件删除
  function deleteMaterialConfirm() {
    const deleteModal = document.getElementById('deleteConfirmModal');
    const confirmBtn = document.getElementById('confirmDelete');
    
    // 防止重复点击
    if (confirmBtn.disabled) {
      return;
    }
    
    // 禁用确认按钮
    confirmBtn.disabled = true;
    confirmBtn.textContent = '删除中...';
    
    fetch(`/teacher/course/material/${deleteId}/delete`, {
      method: 'DELETE'
    })
    .then(response => {
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }
      return response.text();
    })
    .then(result => {
      if (result === 'ok') {
        alert('课件删除成功！');
        // 重新加载当前章节的课件列表
        if (currentCourseId && deleteChapterId) {
          loadChapterMaterials(currentCourseId, deleteChapterId);
        }
      } else {
        alert('删除失败：' + result);
      }
    })
    .catch(err => {
      console.error('删除课件失败:', err);
      alert('删除失败：' + err.message);
    })
    .finally(() => {
      // 恢复按钮状态
      confirmBtn.disabled = false;
      confirmBtn.textContent = '确认删除';
      deleteModal.style.display = 'none';
    });
  }

  document.addEventListener('DOMContentLoaded', function() {
    // 主导航切换功能
    const navLinks = document.querySelectorAll('.nav-links li');
    const contentSections = document.querySelectorAll('.content-section');

    navLinks.forEach(link => {
      link.addEventListener('click', function() {
        const targetId = this.getAttribute('data-target');

        // 更新活跃导航项
        navLinks.forEach(item => item.classList.remove('active'));
        this.classList.add('active');

        // 显示对应内容区域
        contentSections.forEach(section => {
          section.classList.remove('active');
          if (section.id === targetId) {
            section.classList.add('active');
          }
        });
      });
    });

    // 课程详情切换功能
    const courseTabs = document.querySelectorAll('.course-tab');
    const tabContents = document.querySelectorAll('.tab-content');

    courseTabs.forEach(tab => {
      tab.addEventListener('click', function() {
        const tabId = this.getAttribute('data-tab');

        // 更新活跃标签
        courseTabs.forEach(t => t.classList.remove('active'));
        this.classList.add('active');

        // 显示对应内容
        tabContents.forEach(content => {
          content.classList.remove('active');
          if (content.id === `${tabId}-tab`) {
            content.classList.add('active');
          }
        });
        
        // 如果切换到学生列表，加载学生数据
        if (tabId === 'students' && currentCourseId) {
          loadCourseStudents(currentCourseId);
        }
        
        // 如果切换到作业管理，加载作业数据
        if (tabId === 'assignments' && currentCourseId) {
          loadCourseHomeworks(currentCourseId);
        }
      });
    });

    // 进入课程功能（事件委托，支持动态渲染的课程卡片）
    const backToCoursesButton = document.getElementById('back-to-courses');
    
    document.addEventListener('click', function (e) {
      const btn = e.target.closest('.enter-course');
      if (!btn) return;
      const courseId = btn.getAttribute('data-course');
      currentCourseId = courseId; // 保存当前课程ID
      const card = btn.closest('.card');
      const titleEl = card ? card.querySelector('.card-header h4') : null;

      // 隐藏所有内容区域
      contentSections.forEach(section => section.classList.remove('active'));

      // 显示课程详情
      document.getElementById('course-detail').classList.add('active');

      // 设置课程名称
      const nameEl = document.getElementById('detail-course-name');
      if (nameEl && titleEl) nameEl.textContent = titleEl.textContent;

      // 加载章节列表
      loadCourseChapters(courseId);
    });

    // 返回课程列表功能
    backToCoursesButton.addEventListener('click', function() {
      // 隐藏课程详情
      document.getElementById('course-detail').classList.remove('active');

      // 显示我的课程
      document.getElementById('my-courses').classList.add('active');

      // 更新导航状态
      navLinks.forEach(item => {
        item.classList.remove('active');
        if (item.getAttribute('data-target') === 'my-courses') {
          item.classList.add('active');
        }
      });
    });

    // 更新课程详情信息
    function updateCourseDetail(courseId) {
      const courses = {
        '1': {
          name: '高等数学',
          info: '已开课 · 128名学生 · 12章节'
        },
        '2': {
          name: 'Java程序设计',
          info: '已开课 · 96名学生 · 10章节'
        }
      };

      const course = courses[courseId];
      if (course) {
        document.getElementById('detail-course-name').textContent = course.name;
        document.getElementById('detail-course-info').textContent = course.info;
      }
    }

    // 创建课程表单提交
    const courseForm = document.getElementById('course-form');
    courseForm.addEventListener('submit', function(e) {
      e.preventDefault();

      const title = document.getElementById('course-name').value;
      const description = document.getElementById('course-description').value;

      const formData = new URLSearchParams();
      formData.append('title', title);
      formData.append('description', description);

      fetch('/teacher/course/add', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: formData.toString()
      }).then(r => r.text())
        .then(text => {
          alert(text === 'ok' ? '课程创建成功！' : text);
          if (text === 'ok') {
            courseForm.reset();
            // 切换到我的课程页面
            navLinks.forEach(item => {
              item.classList.remove('active');
              if (item.getAttribute('data-target') === 'my-courses') {
                item.classList.add('active');
              }
            });
            contentSections.forEach(section => {
              section.classList.remove('active');
              if (section.id === 'my-courses') {
                section.classList.add('active');
              }
            });
          }
        })
        .catch(err => {
          console.error(err);
          alert('创建失败，请稍后重试');
        });
    });

    // 加载当前教师的课程列表
    function loadMyCourses() {
      fetch('/teacher/course/list').then(r => r.json()).then(list => {
        const container = document.getElementById('my-course-list');
        container.innerHTML = '';
        if (!Array.isArray(list) || list.length === 0) {
          container.innerHTML = '<div style="color:#666;">暂无课程</div>';
          return;
        }
        list.forEach(item => {
          const card = document.createElement('div');
          card.className = 'card';
          card.innerHTML = `
            <div class="card-header">
              <h4>${item.title ?? ''}</h4>
              <p>${item.status === 1 ? '已创建' : ''}</p>
            </div>
            <div class="card-body">
              <p>${item.description ?? ''}</p>
            </div>
            <div class="card-footer">
              <button class="btn btn-outline">课程统计</button>
              <button class="btn btn-primary enter-course" data-course="${item.id}">进入课程</button>
            </div>`;
          container.appendChild(card);
        });
      }).catch(err => console.error(err));
    }



    // 模态框功能
    const modal = document.getElementById('addChapterModal');
    const closeBtn = document.querySelector('.close');
    const cancelBtn = document.getElementById('cancelChapter');
    const addChapterForm = document.getElementById('addChapterForm');

    // 打开模态框
    function openAddChapterModal() {
      if (!currentCourseId) {
        alert('请先选择课程');
        return;
      }
      modal.style.display = 'block';
      document.getElementById('chapterTitle').value = '';
    }

    // 关闭模态框
    function closeModal() {
      modal.style.display = 'none';
    }

    // 事件监听
    closeBtn.addEventListener('click', () => closeModal('addChapterModal'));
    cancelBtn.addEventListener('click', () => closeModal('addChapterModal'));
    
    // 点击模态框外部关闭
    window.addEventListener('click', function(event) {
      if (event.target === modal) {
        closeModal('addChapterModal');
      }
    });

    // 表单提交
    addChapterForm.addEventListener('submit', function(e) {
      e.preventDefault();
      const title = document.getElementById('chapterTitle').value.trim();
      if (!title) {
        alert('请输入章节名称');
        return;
      }

      // 提交到后端
      console.log('当前课程ID:', currentCourseId);
      console.log('章节标题:', title);
      console.log('请求体:', `courseId=${currentCourseId}&title=${encodeURIComponent(title)}`);
      
      fetch('/teacher/course/chapter/add', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `courseId=${currentCourseId}&title=${encodeURIComponent(title)}`
      })
      .then(response => {
        console.log('响应状态:', response.status);
        console.log('响应头:', response.headers);
        return response.text();
      })
      .then(result => {
        console.log('响应内容:', JSON.stringify(result));
        console.log('响应长度:', result.length);
        console.log('是否等于ok:', result === 'ok');
        
        // 更健壮的判断逻辑
        const trimmedResult = result.trim();
        if (trimmedResult === 'ok' || trimmedResult.includes('ok')) {
          closeModal('addChapterModal');
          // 重新加载章节列表
          loadCourseChapters(currentCourseId);
          alert('章节添加成功');
        } else {
          alert('添加失败：' + result);
        }
      })
      .catch(err => {
        console.error(err);
        alert('添加失败，请重试');
      });
    });

    // 为添加章节按钮添加事件监听
    const addChapterBtn = document.getElementById('add-chapter-btn');
    if (addChapterBtn) {
      addChapterBtn.addEventListener('click', function() {
        openAddChapterModal();
      });
    }

    // 课件上传相关功能
    let currentChapterId = null;
    const uploadModal = document.getElementById('uploadMaterialModal');
    const closeUploadBtn = document.getElementById('closeUploadModal');
    const cancelUploadBtn = document.getElementById('cancelUpload');
    const uploadForm = document.getElementById('uploadMaterialForm');

    // 打开课件上传模态框
    function openUploadModal(chapterId) {
      currentChapterId = chapterId;
      uploadModal.style.display = 'block';
      document.getElementById('materialFile').value = '';
      document.getElementById('materialName').value = '';
    }

    // 关闭课件上传模态框
    function closeUploadModal() {
      uploadModal.style.display = 'none';
      currentChapterId = null;
    }

    // 事件监听
    closeUploadBtn.addEventListener('click', closeUploadModal);
    cancelUploadBtn.addEventListener('click', closeUploadModal);
    
    // 点击模态框外部关闭
    window.addEventListener('click', function(event) {
      if (event.target === uploadModal) {
        closeUploadModal();
      }
    });

    // 课件上传表单提交
    uploadForm.addEventListener('submit', function(e) {
      e.preventDefault();
      
      const fileInput = document.getElementById('materialFile');
      const nameInput = document.getElementById('materialName');
      
      if (!fileInput.files[0]) {
        alert('请选择要上传的文件');
        return;
      }
      
      if (!nameInput.value.trim()) {
        alert('请输入文件名称');
        return;
      }
      
      const formData = new FormData();
      formData.append('file', fileInput.files[0]);
      formData.append('name', nameInput.value.trim());
      formData.append('courseId', currentCourseId);
      formData.append('chapterId', currentChapterId);
      // uploaderId 将在后端从session中获取
      
      // 显示上传进度
      const submitBtn = uploadForm.querySelector('button[type="submit"]');
      const originalText = submitBtn.textContent;
      submitBtn.textContent = '上传中...';
      submitBtn.disabled = true;
      
      fetch('/teacher/course/material/upload', {
        method: 'POST',
        body: formData
      })
      .then(response => response.text())
      .then(result => {
        if (result === 'ok') {
          alert('课件上传成功！');
          closeUploadModal();
          // 重新加载当前章节的课件列表
          if (currentCourseId && currentChapterId) {
            loadChapterMaterials(currentCourseId, currentChapterId);
          }
        } else {
          alert('上传失败：' + result);
        }
      })
      .catch(err => {
        console.error(err);
        alert('上传失败，请重试');
      })
      .finally(() => {
        submitBtn.textContent = originalText;
        submitBtn.disabled = false;
      });
    });



    // 为上传课件按钮添加事件监听（事件委托）
    document.addEventListener('click', function(e) {
      if (e.target.closest('.upload-material')) {
        const btn = e.target.closest('.upload-material');
        const chapterId = btn.getAttribute('data-chapter');
        openUploadModal(chapterId);
      }
    });

    // 删除确认模态框元素
    const deleteModal = document.getElementById('deleteConfirmModal');
    const deleteMessage = document.getElementById('deleteMessage');
    const confirmDeleteBtn = document.getElementById('confirmDelete');
    const cancelDeleteBtn = document.getElementById('cancelDelete');
    const closeDeleteBtn = document.getElementById('closeDeleteModal');

    // 删除确认模态框事件监听
    confirmDeleteBtn.addEventListener('click', confirmDelete);
    cancelDeleteBtn.addEventListener('click', () => {
      deleteModal.style.display = 'none';
    });
    closeDeleteBtn.addEventListener('click', () => {
      deleteModal.style.display = 'none';
    });

    // 章节删除按钮事件监听（事件委托）
    document.addEventListener('click', function(e) {
      if (e.target.closest('.delete-chapter')) {
        const btn = e.target.closest('.delete-chapter');
        const chapterId = btn.getAttribute('data-chapter');
        const chapterName = btn.getAttribute('data-chapter-name');
        deleteChapter(chapterId, chapterName);
      }
    });

    // 作业管理模态框事件监听
    const homeworkModal = document.getElementById('homeworkModal');
    const editHomeworkModal = document.getElementById('editHomeworkModal');
    const homeworkForm = document.getElementById('homeworkForm');
    const editHomeworkForm = document.getElementById('editHomeworkForm');

    // 布置作业模态框
    document.getElementById('closeHomeworkModal').addEventListener('click', () => {
      homeworkModal.style.display = 'none';
    });
    document.getElementById('cancelHomework').addEventListener('click', () => {
      homeworkModal.style.display = 'none';
    });
    homeworkForm.addEventListener('submit', function(e) {
      e.preventDefault();
      submitHomeworkForm();
    });

    // 编辑作业模态框
    document.getElementById('closeEditHomeworkModal').addEventListener('click', () => {
      editHomeworkModal.style.display = 'none';
    });
    document.getElementById('cancelEditHomework').addEventListener('click', () => {
      editHomeworkModal.style.display = 'none';
    });
    editHomeworkForm.addEventListener('submit', function(e) {
      e.preventDefault();
      submitEditHomeworkForm();
    });

    // 加载课程学生列表
    function loadCourseStudents(courseId) {
      const loadingDiv = document.getElementById('students-loading');
      const container = document.getElementById('student-list-container');
      const noStudentsDiv = document.getElementById('no-students');
      
      // 显示加载状态
      loadingDiv.style.display = 'block';
      container.innerHTML = '';
      noStudentsDiv.style.display = 'none';
      
      fetch(`/teacher/course/${courseId}/students`)
        .then(response => {
          if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
          }
          return response.json();
        })
        .then(students => {
          loadingDiv.style.display = 'none';
          
          if (!Array.isArray(students) || students.length === 0) {
            noStudentsDiv.style.display = 'block';
            return;
          }
          
          students.forEach(student => {
            const studentItem = document.createElement('li');
            studentItem.className = `student-item ${getStatusClass(student.status)}`;
            
            const statusText = getStatusText(student.status);
            const statusClass = getStatusClass(student.status);
            
            studentItem.innerHTML = `
              <div class="student-info">
                <div class="student-avatar">${student.username ? student.username.charAt(0) : '?'}</div>
                <div>
                  <div style="font-weight: 500;">${student.username || '未知用户'}</div>
                  <div style="font-size: 14px; color: var(--secondary);">
                    ${student.email || ''} · 申请时间: ${student.request_time || ''}
                  </div>
                  ${student.remark ? `<div style="font-size: 12px; color: #666; margin-top: 2px;">备注: ${student.remark}</div>` : ''}
                </div>
              </div>
              <div style="display: flex; align-items: center; gap: 10px;">
                <span class="status-badge ${statusClass}">${statusText}</span>
                ${student.status === 0 ? `
                  <div class="approval-buttons">
                    <button class="btn btn-success btn-sm approve-btn" data-user-id="${student.user_id}" data-course-id="${student.course_id}">
                      <i class="fas fa-check"></i> 批准
                    </button>
                    <button class="btn btn-outline btn-sm reject-btn" data-user-id="${student.user_id}" data-course-id="${student.course_id}">
                      <i class="fas fa-times"></i> 拒绝
                    </button>
                  </div>
                ` : ''}
              </div>`;
            
            container.appendChild(studentItem);
          });
        })
        .catch(error => {
          loadingDiv.style.display = 'none';
          container.innerHTML = `
            <li style="text-align: center; color: #c62828; padding: 20px;">
              <i class="fas fa-exclamation-triangle"></i>
              <div>加载失败: ${error.message}</div>
            </li>`;
        });
    }
    
    // 获取状态文本
    function getStatusText(status) {
      switch (status) {
        case 0: return '待审批';
        case 1: return '已批准';
        case 2: return '已拒绝';
        case 3: return '已退课';
        default: return '未知状态';
      }
    }
    
    // 获取状态样式类
    function getStatusClass(status) {
      switch (status) {
        case 0: return 'pending';
        case 1: return 'approved';
        case 2: return 'rejected';
        case 3: return 'rejected';
        default: return '';
      }
    }
    
    // 审批学生选课
    function approveEnrollment(userId, courseId) {
      const remark = prompt('请输入审批备注（可选）:');
      if (remark === null) return; // 用户取消
      
      fetch('/teacher/enrollment/approve', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ 
          userId: userId,
          courseId: courseId,
          remark: remark || '' 
        })
      })
      .then(response => response.text())
      .then(result => {
        if (result === 'ok') {
          alert('审批成功！');
          // 重新加载学生列表
          if (currentCourseId) {
            loadCourseStudents(currentCourseId);
          }
        } else {
          alert('审批失败: ' + result);
        }
      })
      .catch(error => {
        console.error(error);
        alert('审批失败，请重试');
      });
    }
    
    // 拒绝学生选课
    function rejectEnrollment(userId, courseId) {
      const remark = prompt('请输入拒绝原因（必填）:');
      if (!remark || remark.trim() === '') {
        alert('请输入拒绝原因');
        return;
      }
      
      fetch('/teacher/enrollment/reject', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ 
          userId: userId,
          courseId: courseId,
          remark: remark.trim() 
        })
      })
      .then(response => response.text())
      .then(result => {
        if (result === 'ok') {
          alert('拒绝成功！');
          // 重新加载学生列表
          if (currentCourseId) {
            loadCourseStudents(currentCourseId);
          }
        } else {
          alert('拒绝失败: ' + result);
        }
      })
      .catch(error => {
        console.error(error);
        alert('拒绝失败，请重试');
      });
    }
    
    // 事件委托处理审批按钮点击
    document.addEventListener('click', function(e) {
      if (e.target.closest('.approve-btn')) {
        const btn = e.target.closest('.approve-btn');
        const userId = parseInt(btn.getAttribute('data-user-id'));
        const courseId = parseInt(btn.getAttribute('data-course-id'));
        if (confirm('确定要批准这个学生的选课申请吗？')) {
          approveEnrollment(userId, courseId);
        }
      } else if (e.target.closest('.reject-btn')) {
        const btn = e.target.closest('.reject-btn');
        const userId = parseInt(btn.getAttribute('data-user-id'));
        const courseId = parseInt(btn.getAttribute('data-course-id'));
        if (confirm('确定要拒绝这个学生的选课申请吗？')) {
          rejectEnrollment(userId, courseId);
        }
      } else if (e.target.closest('#refresh-students')) {
        if (currentCourseId) {
          loadCourseStudents(currentCourseId);
        }
      } else if (e.target.closest('#create-homework-btn')) {
        openHomeworkModal();
      } else if (e.target.closest('.edit-homework')) {
        const btn = e.target.closest('.edit-homework');
        const homeworkId = parseInt(btn.getAttribute('data-homework-id'));
        openEditHomeworkModal(homeworkId);
      } else if (e.target.closest('.delete-homework')) {
        const btn = e.target.closest('.delete-homework');
        const homeworkId = parseInt(btn.getAttribute('data-homework-id'));
        deleteHomework(homeworkId);
      } else if (e.target.closest('.view-submissions')) {
        const btn = e.target.closest('.view-submissions');
        const homeworkId = parseInt(btn.getAttribute('data-homework-id'));
        openSubmissionsModal(homeworkId);
      }
    });

    // ==================== 作业管理相关函数 ====================
    
    // 加载课程作业列表
    function loadCourseHomeworks(courseId) {
      const loadingDiv = document.getElementById('homework-loading');
      const container = document.getElementById('homework-list-container');
      const noHomeworkDiv = document.getElementById('no-homework');
      const homeworkList = document.getElementById('homework-list');
      
      // 显示加载状态
      loadingDiv.style.display = 'block';
      noHomeworkDiv.style.display = 'none';
      homeworkList.innerHTML = '';
      
      fetch(`/teacher/course/${courseId}/homeworks`)
        .then(response => {
          if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
          }
          return response.json();
        })
        .then(homeworks => {
          loadingDiv.style.display = 'none';
          
          if (!Array.isArray(homeworks) || homeworks.length === 0) {
            noHomeworkDiv.style.display = 'block';
            return;
          }
          
          homeworks.forEach(homework => {
            const homeworkItem = document.createElement('li');
            homeworkItem.className = 'homework-item';
            
            // 计算作业状态
            const now = new Date();
            const ddlTime = new Date(homework.ddl_time);
            const status = getHomeworkStatus(now, ddlTime);
            
            homeworkItem.innerHTML = `
              <div class="homework-header">
                <div class="homework-info">
                  <h5>${homework.title || ''}</h5>
                  <div class="homework-meta">
                    <span><i class="fas fa-calendar"></i> 截止时间: ${formatDateTime(homework.ddl_time)}</span>
                    <span><i class="fas fa-star"></i> 总分: ${homework.total_score}分</span>
                    <span><i class="fas fa-clock"></i> 创建时间: ${formatDateTime(homework.created_at)}</span>
                  </div>
                </div>
                <div class="homework-actions">
                  <span class="homework-status ${status.class}">${status.text}</span>
                  <button class="btn btn-outline btn-sm view-submissions" data-homework-id="${homework.id}">
                    <i class="fas fa-users"></i> 查看提交
                  </button>
                  <button class="btn btn-outline btn-sm edit-homework" data-homework-id="${homework.id}">
                    <i class="fas fa-edit"></i> 编辑
                  </button>
                  <button class="btn btn-outline btn-sm delete-homework" data-homework-id="${homework.id}">
                    <i class="fas fa-trash"></i> 删除
                  </button>
                </div>
              </div>
              <div class="homework-content">
                ${homework.content || ''}
              </div>
            `;
            
            homeworkList.appendChild(homeworkItem);
          });
        })
        .catch(error => {
          loadingDiv.style.display = 'none';
          homeworkList.innerHTML = `
            <li style="text-align: center; color: #c62828; padding: 20px;">
              <i class="fas fa-exclamation-triangle"></i>
              <div>加载失败: ${error.message}</div>
            </li>`;
        });
    }
    
    // 获取作业状态
    function getHomeworkStatus(now, ddlTime) {
      const timeDiff = ddlTime.getTime() - now.getTime();
      const daysDiff = timeDiff / (1000 * 3600 * 24);
      
      if (timeDiff < 0) {
        return { class: 'expired', text: '已过期' };
      } else if (daysDiff <= 1) {
        return { class: 'upcoming', text: '即将截止' };
      } else {
        return { class: 'active', text: '进行中' };
      }
    }
    
    // 格式化日期时间
    function formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return '';
      const date = new Date(dateTimeStr);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    }
    
    // 打开布置作业模态框
    function openHomeworkModal() {
      const modal = document.getElementById('homeworkModal');
      const form = document.getElementById('homeworkForm');
      
      // 重置表单
      form.reset();
      
      // 设置默认截止时间为明天
      const tomorrow = new Date();
      tomorrow.setDate(tomorrow.getDate() + 1);
      tomorrow.setHours(23, 59, 0, 0);
      document.getElementById('homeworkDdlTime').value = tomorrow.toISOString().slice(0, 16);
      
      modal.style.display = 'block';
    }
    
    // 打开编辑作业模态框
    function openEditHomeworkModal(homeworkId) {
      const modal = document.getElementById('editHomeworkModal');
      const form = document.getElementById('editHomeworkForm');
      
      // 获取作业详情
      fetch(`/teacher/course/homework/${homeworkId}`)
        .then(response => response.json())
        .then(homework => {
          document.getElementById('editHomeworkId').value = homework.id;
          document.getElementById('editHomeworkTitle').value = homework.title || '';
          document.getElementById('editHomeworkContent').value = homework.content || '';
          document.getElementById('editHomeworkTotalScore').value = homework.total_score || 100;
          
          // 格式化截止时间
          if (homework.ddl_time) {
            const ddlDate = new Date(homework.ddl_time);
            document.getElementById('editHomeworkDdlTime').value = ddlDate.toISOString().slice(0, 16);
          }
          
          modal.style.display = 'block';
        })
        .catch(error => {
          console.error('获取作业详情失败:', error);
          alert('获取作业详情失败: ' + error.message);
        });
    }
    
    // 提交作业表单
    function submitHomeworkForm() {
      const form = document.getElementById('homeworkForm');
      const formData = new FormData(form);
      
      const data = {
        courseId: currentCourseId,
        title: document.getElementById('homeworkTitle').value,
        content: document.getElementById('homeworkContent').value,
        ddlTime: document.getElementById('homeworkDdlTime').value,
        totalScore: parseFloat(document.getElementById('homeworkTotalScore').value)
      };
      
      const submitBtn = form.querySelector('button[type="submit"]');
      const originalText = submitBtn.textContent;
      submitBtn.disabled = true;
      submitBtn.textContent = '布置中...';
      
      fetch('/teacher/course/homework/create', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams(data)
      })
      .then(response => response.text())
      .then(result => {
        if (result === 'ok') {
          alert('作业布置成功！');
          closeModal('homeworkModal');
          // 重新加载作业列表
          if (currentCourseId) {
            loadCourseHomeworks(currentCourseId);
          }
        } else {
          alert('布置失败：' + result);
        }
      })
      .catch(error => {
        console.error('布置作业失败:', error);
        alert('布置失败：' + error.message);
      })
      .finally(() => {
        submitBtn.textContent = originalText;
        submitBtn.disabled = false;
      });
    }
    
    // 提交编辑作业表单
    function submitEditHomeworkForm() {
      const form = document.getElementById('editHomeworkForm');
      const homeworkId = document.getElementById('editHomeworkId').value;
      
      const data = {
        homeworkId: homeworkId,
        title: document.getElementById('editHomeworkTitle').value,
        content: document.getElementById('editHomeworkContent').value,
        ddlTime: document.getElementById('editHomeworkDdlTime').value,
        totalScore: parseFloat(document.getElementById('editHomeworkTotalScore').value)
      };
      
      const submitBtn = form.querySelector('button[type="submit"]');
      const originalText = submitBtn.textContent;
      submitBtn.disabled = true;
      submitBtn.textContent = '保存中...';
      
      fetch('/teacher/course/homework/update', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams(data)
      })
      .then(response => response.text())
      .then(result => {
        if (result === 'ok') {
          alert('作业修改成功！');
          closeModal('editHomeworkModal');
          // 重新加载作业列表
          if (currentCourseId) {
            loadCourseHomeworks(currentCourseId);
          }
        } else {
          alert('修改失败：' + result);
        }
      })
      .catch(error => {
        console.error('修改作业失败:', error);
        alert('修改失败：' + error.message);
      })
      .finally(() => {
        submitBtn.textContent = originalText;
        submitBtn.disabled = false;
      });
    }
    
    // 删除作业
    function deleteHomework(homeworkId) {
      if (confirm('确定要删除这个作业吗？删除后无法恢复！')) {
        fetch(`/teacher/course/homework/${homeworkId}`, {
          method: 'DELETE'
        })
        .then(response => response.text())
        .then(result => {
          if (result === 'ok') {
            alert('作业删除成功！');
            // 重新加载作业列表
            if (currentCourseId) {
              loadCourseHomeworks(currentCourseId);
            }
          } else {
            alert('删除失败：' + result);
          }
        })
        .catch(error => {
          console.error('删除作业失败:', error);
          alert('删除失败：' + error.message);
        });
      }
    }
    
    // 关闭模态框的通用函数
    function closeModal(modalId) {
      const modal = document.getElementById(modalId);
      if (modal) {
        modal.style.display = 'none';
      } else {
        console.warn('模态框元素未找到:', modalId);
      }
    }
    
    // ==================== 作业提交查看相关函数 ====================
    
    // 打开查看提交模态框
    function openSubmissionsModal(homeworkId) {
      const modal = document.getElementById('submissionsModal');
      modal.style.display = 'block';
      loadHomeworkSubmissions(homeworkId);
    }
    
    // 加载作业提交列表
    function loadHomeworkSubmissions(homeworkId) {
      const loadingDiv = document.getElementById('submissions-loading');
      const noSubmissionsDiv = document.getElementById('no-submissions');
      const submissionsList = document.getElementById('submissions-list');
      
      // 显示加载状态
      loadingDiv.style.display = 'block';
      noSubmissionsDiv.style.display = 'none';
      submissionsList.innerHTML = '';
      
      fetch(`/teacher/course/homework/${homeworkId}/submissions`)
        .then(response => {
          if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
          }
          return response.json();
        })
        .then(data => {
          loadingDiv.style.display = 'none';
          
          if (typeof data === 'string') {
            // 错误信息
            submissionsList.innerHTML = `
              <div style="text-align: center; color: #c62828; padding: 20px;">
                <i class="fas fa-exclamation-triangle"></i>
                <div>${data}</div>
              </div>`;
            return;
          }
          
          if (!Array.isArray(data) || data.length === 0) {
            noSubmissionsDiv.style.display = 'block';
            return;
          }
          
          data.forEach(submission => {
            const submissionItem = createSubmissionItem(submission);
            submissionsList.appendChild(submissionItem);
          });
        })
        .catch(error => {
          loadingDiv.style.display = 'none';
          submissionsList.innerHTML = `
            <div style="text-align: center; color: #c62828; padding: 20px;">
              <i class="fas fa-exclamation-triangle"></i>
              <div>加载失败: ${error.message}</div>
            </div>`;
        });
    }
    
    // 创建提交项
    function createSubmissionItem(submission) {
      const item = document.createElement('div');
      item.className = 'submission-item';
      item.style.cssText = `
        border: 1px solid #e0e0e0;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 16px;
        background: white;
      `;
      
      const isGraded = submission.score && submission.score !== '';
      const gradeStatus = isGraded ? '已批改' : '未批改';
      const gradeClass = isGraded ? 'status-graded' : 'status-pending';
      
      item.innerHTML = `
        <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 12px;">
          <div>
            <h5 style="margin: 0 0 8px 0; color: var(--dark);">${submission.username || '学生'}</h5>
            <div style="display: flex; gap: 16px; font-size: 14px; color: var(--secondary);">
              <span><i class="fas fa-clock"></i> 提交时间: ${formatDateTime(submission.submitted_at)}</span>
              <span class="status-badge ${gradeClass}">${gradeStatus}</span>
            </div>
          </div>
          <div>
            ${isGraded ? `
              <span style="font-size: 18px; font-weight: bold; color: var(--success);">
                ${submission.score}分
              </span>
            ` : `
              <button class="btn btn-primary btn-sm grade-submission" data-submission-id="${submission.id}">
                <i class="fas fa-check"></i> 批改
              </button>
            `}
          </div>
        </div>
        <div style="margin-bottom: 12px;">
          <strong>提交内容:</strong>
          <div style="background: #f8f9fa; padding: 12px; border-radius: 4px; margin-top: 8px; white-space: pre-wrap;">
            ${submission.content_text || '无文字内容'}
          </div>
        </div>
        ${submission.feedback ? `
          <div style="margin-bottom: 12px;">
            <strong>教师反馈:</strong>
            <div style="background: #e8f5e8; padding: 12px; border-radius: 4px; margin-top: 8px;">
              ${submission.feedback}
            </div>
          </div>
        ` : ''}
      `;
      
      return item;
    }
    
    // 批改作业
    function gradeSubmission(submissionId) {
      const score = prompt('请输入分数:');
      if (score === null) return;
      
      if (!score || isNaN(score) || score < 0 || score > 100) {
        alert('请输入有效的分数 (0-100)');
        return;
      }
      
      const feedback = prompt('请输入反馈意见 (可选):') || '';
      
      const data = {
        submissionId: submissionId,
        score: score,
        feedback: feedback
      };
      
      fetch('/teacher/course/homework/grade', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams(data)
      })
      .then(response => response.text())
      .then(result => {
        if (result === 'ok') {
          alert('批改成功！');
          // 重新加载提交列表
          const homeworkId = document.querySelector('.view-submissions[data-homework-id]')?.getAttribute('data-homework-id');
          if (homeworkId) {
            loadHomeworkSubmissions(homeworkId);
          }
        } else {
          alert('批改失败：' + result);
        }
      })
      .catch(error => {
        console.error('批改作业失败:', error);
        alert('批改失败：' + error.message);
      });
    }
    
    // 查看提交模态框事件监听
    document.getElementById('closeSubmissionsModal').addEventListener('click', () => {
      closeModal('submissionsModal');
    });
    
    // 批改按钮事件监听
    document.addEventListener('click', function(e) {
      if (e.target.closest('.grade-submission')) {
        const btn = e.target.closest('.grade-submission');
        const submissionId = parseInt(btn.getAttribute('data-submission-id'));
        gradeSubmission(submissionId);
      }
    });

    // 初始加载
    loadMyCourses();
  });
  
  // 退出登录函数
  function logout() {
    if (confirm('确定要退出登录吗？')) {
      window.location.href = '/logout';
    }
  }
</script>
</body>
</html>
